package database

import (
	"fmt"
	"github.com/jinzhu/gorm"
	"github.com/spf13/viper"
	"tyjt-ferry/database/orm"
	"tyjt-ferry/internal/config"
	"tyjt-ferry/pkg/logger"
)

var (
	DbType   string
	Host     string
	Port     int
	Name     string
	Username string
	Password string
)

type Mysql struct {
}

func (e *Mysql) Open(dbType string, conn string) (db *gorm.DB, err error) {
	return gorm.Open(dbType, conn)
}

// 把MySQL的链接信息，组装成一个string返回
func (e *Mysql) GetConnect() string {
	DbType = config.DataBaseConfig.Dbtype
	Host = config.DataBaseConfig.Host
	Port = config.DataBaseConfig.Port
	Name = config.DataBaseConfig.Name
	Username = config.DataBaseConfig.Username
	Password = config.DataBaseConfig.Password

	// username:password@tcp(host:port)/databasename?charset=utf8&parseTime=True&loc=Local&timeout=10000ms
	conn := fmt.Sprintf("%s:%s@tcp(%s:%v)/%s?charset=utf8&parseTime=True&loc=Local&timeout=10000ms",
		Username, Password, Host, Port, Name)
	return conn
}

func (e *Mysql) Setup() {
	var (
		err error
		db  Database
	)
	db = new(Mysql)
	orm.MysqlConn = db.GetConnect()
	orm.Eloquent, err = db.Open(DbType, orm.MysqlConn)
	if err != nil {
		logger.Errorf("%s connect error %v", DbType, err)
	} else {
		logger.Infof("%s connect success ", DbType)
	}

	if orm.Eloquent.Error != nil {
		logger.Fatalf("database error %v", orm.Eloquent.Error)
	}

	orm.Eloquent.LogMode(viper.GetBool("settings.gorm.logMode"))
	orm.Eloquent.DB().SetMaxOpenConns(viper.GetInt("settings.gorm.maxOpenConn"))
	orm.Eloquent.DB().SetMaxIdleConns(viper.GetInt("settings.gorm.maxIdleConn"))

}
